package com.xiaoze.sink;

import com.xiaoze.entity.SensorReading;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

/**
 * SinkTestJdbc
 *
 * @author Lin Zemin
 * @date 2021-12-29
 */
public class SinkTestJdbc {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> stringDataStreamSource = env.readTextFile(System.getProperty("user.dir") + "\\src\\main\\resources\\sensor.txt");

        SingleOutputStreamOperator<SensorReading> dataStream = stringDataStreamSource.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });

        SinkFunction<SensorReading> sink = JdbcSink.sink(
                "insert into test_sensor_reading (id, timeNum, temperature) values (?, ?, ?)",
                (statement, sensorReading) -> {
                    statement.setString(1, sensorReading.getId());
                    statement.setLong(2, sensorReading.getTimeNum());
                    statement.setDouble(3, sensorReading.getTemperature());
                },
                JdbcExecutionOptions.builder()
                        .withBatchSize(1000)
                        .withBatchIntervalMs(200)
                        .withMaxRetries(5)
                        .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withUrl("jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&autoReconnect=true&noAccessToProcedureBodies=true")
                        .withDriverName("com.mysql.cj.jdbc.Driver")
                        .withUsername("xiaoze")
                        .withPassword("123456")
                        .build()
        );

        dataStream.addSink(sink);

        env.execute();

    }

}
